//
//  Toast.swift
//  
//
//  Created by tank on 2021/12/5.
//

import Foundation
import UIKit
import SwiftMessages

public class Toast {
    public enum ToastType {
        case loading
    }
    
    public typealias ToastCompletion = () -> Void
    
    public static let shared: Toast = Toast()
    
    private init() {
        
    }
    
    public func loading(message: String, interactive: Bool?, duration: TimeInterval? = nil, completion: ToastCompletion?) {
        toast(type: .loading, message: message, interactive: interactive, duration: duration, completion: completion)
    }
    
    public func toast(type: ToastType?, message: String,
                      interactive: Bool?, duration: TimeInterval?, completion: ToastCompletion?) {
        let toastView = ToastView(type: type, message: message)
        
        var config = SwiftMessages.defaultConfig
        config.presentationStyle = .center
        config.dimMode = .gray(interactive: interactive ?? false)
        config.duration = duration == nil ? .forever : .seconds(seconds: duration! / 1000)
        config.interactiveHide = interactive ?? false
        config.presentationContext = .window(windowLevel: .alert)
        config.preferredStatusBarStyle = UIViewController.ex.topMost?
            .preferredStatusBarStyle
        config.eventListeners.append { event in
            if case .didHide(_) = event {
                completion?()
            }
        }
        SwiftMessages.show(config: config, view: toastView)
    }
    
    public func closeToast() {
        SwiftMessages.hideAll()
    }
}
